package com.fingard.dsp.bank.directbank.wrcb01;

import com.fingard.FGBiz;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.sql.Connection;
import java.util.Map;
import java.util.UUID;

public class WRCB01SinglePay extends WRCB01Base implements ISinglePay {
    private static final String INSERTRECEIPT = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,REQSEQID,BANKREQSEQID) values (?,?,?,?);";
    private static final String SELECTRECEIPT = "SELECT BANKREQSEQID FROM REQSEQIDMAPPING WHERE REQSEQID=? and BANKCODE=?;";

    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
        Connection conn = FGBiz.getLocalDbConn();
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            xmlWriter.writeStartElement("Message");
            xmlWriter.writeStartElement("Head");
            xmlWriter.writeElementString("TrsCode", "B2EBatchTransfer");//交易码
            xmlWriter.writeElementString("ERPTrsTimestamp", p_req1908.reqHeader.transTime);//客户端时间
            xmlWriter.writeElementString("ERPJnlNo", p_req1908.singleDetail.askNumber);//客户流水号
            xmlWriter.writeStartElement("Body");
            xmlWriter.writeStartElement("List");
            xmlWriter.writeStartElement("Map");
            xmlWriter.writeElementString("TransferType", p_req1908.singleDetail.sameBnk.equals("1") ? "001" : "002");//同行标志 001行内转账 002跨行转账
            xmlWriter.writeElementString("PayerAcNo", p_req1908.singleDetail.payAct);//付款方账号
            xmlWriter.writeElementString("PayerAcName", p_req1908.singleDetail.payName);//付款方名
            xmlWriter.writeElementString("PayerCurrency", convertCurToBank(p_req1908.singleDetail.payCur));//付款币种
            xmlWriter.writeElementString("PayeeAcName", p_req1908.singleDetail.recName);//收款方名
            xmlWriter.writeElementString("PayeeAcNo", p_req1908.singleDetail.recAct);//收款方账号
            xmlWriter.writeElementString("Amount", p_req1908.singleDetail.payAmount);//付款金额
            xmlWriter.writeElementString("UnionDeptId", p_req1908.singleDetail.cnapsCode);//行号
            xmlWriter.writeElementString("Priority", p_req1908.singleDetail.paySpd);//加急标志
            xmlWriter.writeElementString("Remark", p_req1908.singleDetail.abstractATS);//附言（这里传对账码）
            xmlWriter.writeElementString("PayerBankAcType", "");//付款人帐户类型
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String returnCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String returnMsg = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                    String bankSeqNo = tmpBkReader.getFirstText("/Message/Head/IBSJnlNo");//银行流水号
                    if (returnCode.equals("000000")) {
                        String tmpRespCode = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnCode");
                        String tmpRespInfo = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnMsg");//正确返回空
                        tmpRetAtsDetail.respCode = "0";
                        tmpRetAtsDetail.respInfo = StringHelper.isNullOrEmpty(tmpRespInfo) ? "处理成功" : tmpRespInfo;
                        tmpRetAtsDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                        tmpRetAtsDetail.transState = tmpRespCode;
                        tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                        if (!StringHelper.isNullOrEmpty(bankSeqNo)) {
                            //存入银行返回的流水号，查询交易结果使用
                            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                            JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{uuid, p_req1908.reqHeader.bankCode, p_req1908.singleDetail.askNumber, bankSeqNo});
                        }
                    } else {
                        tmpRetAtsDetail.respCode = "0";
                        tmpRetAtsDetail.respInfo = returnMsg;
                        tmpRetAtsDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                        tmpRetAtsDetail.transState = returnCode;
                        tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                    }
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("转账支付时候出现异常！");
            WriteBankLogLn("转账支付时候出现异常,异常信息：" + e.getMessage());
        } finally {
            conn.close();
        }
        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        Connection conn = FGBiz.getLocalDbConn();
        try {
            xmlWriter.writeStartElement("Message");
            xmlWriter.writeStartElement("Head");
            xmlWriter.writeElementString("TrsCode", "B2EBatchTrsResQry");//交易码
            xmlWriter.writeElementString("ERPTrsTimestamp", p_req1944.reqHeader.transTime);//客户端时间
            xmlWriter.writeElementString("ERPJnlNo", p_req1944.askNumber);//客户流水号
            xmlWriter.writeStartElement("Body");
            Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{p_req1944.askNumber, p_req1944.reqHeader.bankCode});
            if (map.size() == 0) {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = "没有这条请求映射的流水号！";
                retAts.writeRetDetail(tmpRetAtsDetail);
                return retAts;
            }
            xmlWriter.writeElementString("HistoryERPJnlNo", map.get("BANKREQSEQID").toString());
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String returnCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String returnMsg = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                    if (returnCode.equals("000000")) {
                        String respCode = tmpBkReader.getFirstText("/Message/Body/List/Map/TransStateCode");
                        String respInfo = tmpBkReader.getFirstText("/Message/Body/List/Map/TransStateMsg");
                        tmpRetAtsDetail.respCode = "0";
                        tmpRetAtsDetail.respInfo = respInfo;
                        tmpRetAtsDetail.transState = respCode;
                        tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                    } else {
                        tmpRetAtsDetail.respCode = "-1";
                        tmpRetAtsDetail.respInfo = returnMsg;
                    }
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetAtsDetail.respCode = "-1";
            tmpRetAtsDetail.respInfo = "交易结果状态查询出现异常！";
            WriteBankLogLn("交易结果状态查询出现异常,异常信息:" + e.getMessage());
            e.printStackTrace();
        } finally {
            conn.close();
        }
        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
